<template>
  <div id="teamPage">
    <van-form @submit="onSubmit">
      <van-cell-group inset>


        <van-field name="uploader" label="文件上传">
          <template #input>
            <van-uploader @after-read="onAfterRead"/>
          </template>
        </van-field>

        <!-- 队伍名 -->
        <van-field
            v-model="addTeamData.name"
            name="name"
            label="队伍名"
            placeholder="请输入队伍名"
            :rules="[{ required: true, message: '请输入队伍名' }]"
        />
        <!-- 队伍描述 -->
        <van-field
            v-model="addTeamData.description"
            rows="4"
            autosize
            label="队伍描述"
            type="textarea"
            placeholder="请输入队伍描述"
        />
        <!-- 过期时间 -->
        <van-field
            v-model="currentDate"
            is-link
            readonly
            name="datePicker"
            label="过期时间"
            :placeholder="addTeamData.expireTime ? formatDate(addTeamData.expireTime) : '点击选择过期时间'"
            @click="showDatePicker = true"
        />

        <!-- 时间选择器 -->
        <van-popup v-model:show="showDatePicker" destroy-on-close position="bottom">
          <van-date-picker
              title="请选择日期"
              :min-date="minDate"
              @confirm="onConfirmDate"
              @cancel="showDatePicker = false"
          />
        </van-popup>


        <!-- 最大人数 -->
        <van-field name="stepper" label="最大人数">
          <template #input>
            <van-stepper v-model="addTeamData.maxNum" :max="10" :min="3" />
          </template>
        </van-field>

        <!-- 队伍状态 -->
        <van-field name="radio" label="队伍状态">
          <template #input>
            <van-radio-group v-model="addTeamData.status" direction="horizontal">
              <van-radio :name="0">公开</van-radio>
              <van-radio :name="1">私有</van-radio>
              <van-radio :name="2">加密</van-radio>
            </van-radio-group>
          </template>
        </van-field>

        <!-- 密码输入框（仅当状态为加密时显示） -->
        <van-field
            v-if="Number(addTeamData.status) === 2"
            v-model="addTeamData.password"
            type="password"
            name="password"
            label="密码"
            placeholder="请输入队伍密码"
            :rules="[{ required: true, message: '请填写密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button :loading="loading" round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import myAxios from '../plugins/myAxios.ts';
import { showSuccessToast, showFailToast } from 'vant';
import dayjs from 'dayjs';

const router = useRouter();

// 初始化表单数据（确保 status 是数值类型）
const initFormData = {
  name: '',
  description: '',
  expireTime: '',
  maxNum: 3,
  password: '',
  status: 0, // 数值类型 0/1/2
  userId: 0,
  //默认值
  avatarUrl : '',
};
const addTeamData = ref({ ...initFormData });
const ImageAvatarUrl = ref([
  { url: '' },
]);
// 控制日期和时间选择器的显示状态
let showDatePicker = ref(false);
let currentDate = ref('');
const minDate = new Date(2020, 0, 1);


// 日期选择确认
const onConfirmDate = ({ selectedValues }) => {
  currentDate  = selectedValues.join('/');
  addTeamData.value.expireTime = selectedValues;
  showDatePicker.value = false;
};

// 格式化日期时间
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD');
};

// 提交表单（增强校验逻辑）
const onSubmit = async () => {
  // 基础校验
  if (!addTeamData.value.name) {
    showFailToast('请输入队伍名');
    return;
  }
  if (!addTeamData.value.expireTime) {
    showFailToast('请选择过期时间');
    return;
  }

  // 校验过期时间是否合法
  const expireTime = dayjs(addTeamData.value.expireTime);
  if (expireTime.isBefore(dayjs())) {
    showFailToast('过期时间不能早于当前时间');
    return;
  }

  // 加密队伍需校验密码
  if (Number(addTeamData.value.status) === 2 && !addTeamData.value.password) {
    showFailToast('请填写密码');
    return;
  }

  // 提交数据（确保 status 是数值类型）对象展开运算符（spread operator）来复制 addTeamData 对象的值
  const postData = {
    ...addTeamData.value,
    status: Number(addTeamData.value.status),
    expireTime: formatDate(addTeamData.value.expireTime),
  };

  try {
    const res = await myAxios.post('/team/add', postData);
    if (res?.code === 0 && res.data) {
      showSuccessToast('添加成功');
      router.push({ path: '/team', replace: true });
    } else {
      showFailToast(res?.message || '添加失败');
    }
  } catch (error) {
    showFailToast('请求失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};



// 文件上传成功后的处理
const onAfterRead = (file) => {
  uploadFile(file.file).then(url => {
    addTeamData.value.avatarUrl = url;
    postData.avatarUrl=url;
  }).catch(err => {
    showFailToast('文件上传失败，请稍后重试');
  });
};






</script>

<style scoped>
#teamPage {
  padding: 16px;
}
</style>